#!/usr/bin/env python
# -*- coding: utf-8 -*-

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import List, Optional
from app.core.database import get_db
from app.core.security import get_current_active_user, get_password_hash
from app.models.base_model import User
from pydantic import BaseModel
from datetime import datetime

router = APIRouter()

# 用户返回模型
class UserOut(BaseModel):
    id: int
    username: str
    role_id: int
    status: int
    create_time: datetime
    update_time: Optional[datetime] = None

    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda dt: dt.isoformat() if dt else None
        }

# 用户更新模型
class UserUpdate(BaseModel):
    password: Optional[str] = None
    role_id: Optional[int] = None
    status: Optional[int] = None

# 用户搜索参数模型
class UserSearch(BaseModel):
    keyword: Optional[str] = None  # 搜索关键词
    role_id: Optional[int] = None  # 角色ID
    status: Optional[int] = None   # 状态

# 用户日志模型
class UserLog(BaseModel):
    id: int
    user_id: int
    username: str
    action: str
    action_time: datetime
    ip_address: Optional[str] = None
    details: Optional[str] = None

    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda dt: dt.isoformat() if dt else None
        }

# 用户创建模型
class UserCreate(BaseModel):
    username: str
    password: str
    role_id: int
    status: int = 1

@router.get("", response_model=List[UserOut])
async def get_users(
    skip: int = 0,
    limit: int = 10,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取用户列表"""
    # 检查权限
    if current_user.role_id != 1:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看用户列表"
        )
    users = db.query(User).offset(skip).limit(limit).all()
    return users

@router.get("/{user_id}", response_model=UserOut)
async def get_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取单个用户信息"""
    # 检查权限
    if current_user.role_id != 1:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看用户信息"
        )
    
<<<<<<< HEAD
    # 找用户
=======
    # ���找用户
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    return user

@router.put("/{user_id}", response_model=UserOut)
async def update_user(
    user_id: int,
    user_update: UserUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新用户信息"""
    # 检查权限
    if current_user.role_id != 1:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限执行此操作"
        )
    
    # 查找用户
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 不能修改自己的角色
    if user_id == current_user.id and user_update.role_id is not None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能修改自己的角色"
        )
    
    # 更新密码
    if user_update.password:
        db_user.password_hash = get_password_hash(user_update.password)
    
    # 更新角色
    if user_update.role_id is not None:
        db_user.role_id = user_update.role_id
    
    # 更新状态
    if user_update.status is not None:
        db_user.status = user_update.status
    
    # 更新时间
    db_user.update_time = datetime.now()
    
    db.commit()
    db.refresh(db_user)
    return db_user

@router.patch("/{user_id}/status", response_model=UserOut)
async def toggle_user_status(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """切换用户状态（启用/禁用）"""
    # 检查权限
    if current_user.role_id != 1:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限执行此操作"
        )
    
    # 查找用户
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 不能禁用自己
    if user_id == current_user.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能禁用自己的账号"
        )
    
    # 检查是否是最后一个管理员
    if db_user.role_id == 1 and db_user.status == 1:
        admin_count = db.query(User).filter(
            User.role_id == 1,
            User.status == 1,
            User.id != user_id
        ).count()
        if admin_count == 0:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="不能禁用最后一个管理员账号"
            )
    
    # 切换状态
    db_user.status = 0 if db_user.status == 1 else 1
    db_user.update_time = datetime.now()
    
    db.commit()
    db.refresh(db_user)
    return db_user 

@router.post("/search", response_model=List[UserOut])
async def search_users(
    search: UserSearch,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """搜索用户"""
    # 检查权限
    if current_user.role_id != 1:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限搜索用户"
        )
    
    # 构建查询
    query = db.query(User)
    
    # 关键词搜索
    if search.keyword:
        query = query.filter(
            or_(
                User.username.ilike(f"%{search.keyword}%")
            )
        )
    
    # 角色筛选
    if search.role_id is not None:
        query = query.filter(User.role_id == search.role_id)
    
    # 状态筛选
    if search.status is not None:
        query = query.filter(User.status == search.status)
    
    users = query.all()
    return users

@router.get("/{user_id}/logs", response_model=List[UserLog])
async def get_user_logs(
    user_id: int,
    skip: int = 0,
    limit: int = 50,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取用户操作日志"""
    # 检查权限
    if current_user.role_id != 1:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看用户日志"
        )
    
    # 检查用户是否存在
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # TODO: 实现日志查询
    # 这里需要添加用户日志表和相关查询
    # 暂时返回示例数据
    logs = [
        {
            "id": 1,
            "user_id": user_id,
            "username": user.username,
            "action": "登录系统",
            "action_time": datetime.now(),
            "ip_address": "127.0.0.1",
            "details": "正常登录"
        }
    ]
    
<<<<<<< HEAD
    return logs 

@router.post("", response_model=UserOut)
async def create_user(
    user: UserCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建新用户"""
    # 检查权限
    if current_user.role_id != 1:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限创建用户"
        )
    
    # 检查用户名是否已存在
    if db.query(User).filter(User.username == user.username).first():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在"
        )
    
    # 创建新用户
    db_user = User(
        username=user.username,
        password_hash=get_password_hash(user.password),
        role_id=user.role_id,
        status=user.status
    )
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user 
=======
    return logs 
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
